package scatter.wxmp.rest.security;

import me.chanjar.weixin.mp.api.WxMpService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import scatter.common.rest.config.CommonRestSecurityConfigure;
import scatter.common.rest.security.DefaultAuthenticationFailureHandler;
import scatter.common.rest.security.DefaultAuthenticationSuccessHandler;

/**
 * Created by yangwei
 * Created at 2021/1/6 16:46
 */
public class WxMpWebSecurityConfig implements CommonRestSecurityConfigure {

    public static String wxMpLoginUrl = "/wxmp/oauth2/login";

    @Autowired
    private WxMpUserDetailsServiceImpl wxMpUserDetailsService;
    @Autowired
    private WxMpService wxMpService;

    @Override
    public void configure(HttpSecurity http, AuthenticationManager authenticationManager) throws Exception {
        WxMpCodeAuthenticationFilter mobileAuthenticationFilter = new WxMpCodeAuthenticationFilter();
        mobileAuthenticationFilter.setFilterProcessesUrl(wxMpLoginUrl);
        mobileAuthenticationFilter.setAuthenticationManager(authenticationManager);
        mobileAuthenticationFilter.setAuthenticationSuccessHandler(new DefaultAuthenticationSuccessHandler());
        mobileAuthenticationFilter.setAuthenticationFailureHandler(new DefaultAuthenticationFailureHandler());

        http.addFilterAfter(mobileAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);

        //http.authorizeRequests().mvcMatchers(HttpMethod.POST,loginUrl).permitAll();
    }

    @Override
    public void configure(AuthenticationManagerBuilder auth, PasswordEncoder passwordEncoder) throws Exception {

        WxMpCodeAuthenticationProvider mobileAuthenticationProvider = new WxMpCodeAuthenticationProvider();
        mobileAuthenticationProvider.setUserDetailsService(wxMpUserDetailsService);
        mobileAuthenticationProvider.setWxMpService(wxMpService);
        auth.authenticationProvider(mobileAuthenticationProvider);
    }
}
